package com.zichen.pr.system.controller;

import com.zichen.pr.common.constant.Constants;
import com.zichen.pr.common.core.domain.entity.SysMenu;
import com.zichen.pr.common.core.domain.entity.SysUser;
import com.zichen.pr.common.core.domain.model.LoginBody;
import com.zichen.pr.common.core.domain.model.LoginUser;
import com.zichen.pr.common.core.domain.result.Result;
import com.zichen.pr.framework.web.service.SysLoginService;
import com.zichen.pr.framework.web.service.SysPermissionService;
import com.zichen.pr.framework.web.service.TokenService;
import com.zichen.pr.system.service.SysMenuService;
import com.zichen.pr.util.ServletUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;

/**
 * @program: pr
 * @description: 登录验证
 * @author: rzhang
 * @create: 2021-04-02 16:12
 */
@RestController
public class SysLoginController {

    @Resource(name = "loginService")
    private SysLoginService loginService;

    @Resource(name = "sysMenuService")
    private SysMenuService sysMenuService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysPermissionService permissionService;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public Result login(@RequestBody LoginBody loginBody) {
        Result ajax = Result.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(),loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public Result getRouters() {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        // 用户信息
        SysUser user = loginUser.getUser();
        List<SysMenu> menus = sysMenuService.selectMenuTreeByUserId(user.getUserId());
        return Result.success(sysMenuService.buildMenus(menus));
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public Result getInfo() {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser user = loginUser.getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        Result ajax = Result.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }
}
